package com.mac.bluetoothbt.feature;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.jingchen.timerpicker.PickerView;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import static com.mac.bluetoothbt.feature.FrameUtil.VOLUMES;
import static com.mac.bluetoothbt.feature.Main2Activity.DEVICESTATE;

/**
 * @author wyh
 */
public class Setting2Activity extends AppCompatActivity {
    DeviceEntity deviceEntity;
    List<Sensor> sensors = null;
    PickerView picker1, picker2;
    EditText addressEditText;
    List<String> boudrates = new ArrayList<>();
    List<String> volumes = new ArrayList<>();
    private BroadcastReceiver receiver;

    {
        boudrates.addAll(Arrays.asList(FrameUtil.BOUDRATES));
        volumes.addAll(Arrays.asList(VOLUMES));
    }
    @Override
    protected void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
        setContentView(R.layout.setting2);

        Intent intent = getIntent();
        if (intent.hasExtra(DEVICESTATE)){
            deviceEntity = (DeviceEntity) intent.getSerializableExtra(DEVICESTATE);
            sensors = deviceEntity.getSensors();
        }

        IntentFilter filter = new IntentFilter();
        filter.addAction(Actions.ACTION_WRITE_END);
        filter.addAction(Actions.ACTION_WRITE_SUCCESS);
        filter.addAction(Actions.ACTION_WRITE_FAIL);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Actions.ACTION_WRITE_END.equals(intent.getAction())) {
                    if (isWriting) {
                        startActivity(new Intent().setClass(getApplication(), Main2Activity.class).putExtra(DEVICESTATE, deviceEntity));
                        isWriting = false;
                    }
                } else if (Actions.ACTION_WRITE_SUCCESS.equals(intent.getAction())) {
                    Toast.makeText(getApplication()
                            , "设置成功", Toast.LENGTH_LONG)
                            .show();
                    startActivity(new Intent()
                            .setClass(Setting2Activity.this, Main2Activity.class)
                            .putExtra(DEVICESTATE, deviceEntity));
                } else if (Actions.ACTION_WRITE_FAIL.equals(intent.getAction())) {
                    Toast.makeText(getApplication()
                            , "设置失败", Toast.LENGTH_LONG)
                            .show();
                    startActivity(new Intent()
                            .setClass(Setting2Activity.this, Main2Activity.class)
                            .putExtra(DEVICESTATE, deviceEntity));
                }
            }
        };
        registerReceiver(receiver, filter);

        picker1Setting();
        picker2Setting();
        addressEditTextSetting();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
    }

    private void picker1Setting() {
        picker1 = findViewById(R.id.picker1);
        picker1.setData(boudrates);
        int indx = boudrates.indexOf(String.format(Locale.PRC, "%d", deviceEntity.getBoudrate()));
        if (indx >= 0) {picker1.setSelected(indx);}
        picker1.invalidate();
        picker1.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                deviceEntity.setBoudrate(Integer.parseInt(text));
            }
        });
    }

    private void picker2Setting() {
        picker2 = findViewById(R.id.picker2);
        picker2.setData(volumes);
        picker2.setSelected(deviceEntity.getVolume());
        picker2.invalidate();
        picker2.setOnSelectListener(new PickerView.onSelectListener() {
            @Override
            public void onSelect(String text) {
                deviceEntity.setVolume(Integer.parseInt(text));
            }
        });
    }

    private void addressEditTextSetting() {
        addressEditText = findViewById(R.id.editText4);
        addressEditText.setText(String.format(Locale.PRC, "%d", deviceEntity.getAddress()));
        addressEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) { }

            @Override
            public void afterTextChanged(Editable s) {
                int val;
                try{
                    val = Integer.parseInt(s.toString());
                    if (val > 255) {
                        s.replace(0, s.length(), "255");
                        return;
                    } else if (val < 1) {
                        s.replace(0, s.length(), "1");
                        return;
                    }
                }catch (NumberFormatException e){
                    e.printStackTrace();
                    return;
                }

                try {
                    deviceEntity.setAddress(Integer.parseInt(s.toString()));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }



    @Override
    protected void onResume(){
        super.onResume();
        Intent intent = getIntent();
        if (intent.hasExtra(DEVICESTATE)){
            deviceEntity = (DeviceEntity) intent.getSerializableExtra(DEVICESTATE);
            sensors = deviceEntity.getSensors();
        }

        addressEditText.setText(String.format(Locale.PRC, "%d", deviceEntity.getAddress()));

        int indx = boudrates.indexOf(String.format(Locale.PRC, "%d", deviceEntity.getBoudrate()));
        if (indx >= 0) {picker1.setSelected(indx);}
        picker1.invalidate();

        picker2.setSelected(deviceEntity.getVolume());
        picker2.invalidate();
    }

    public void settingNextPageOnClicked(View view){
        startActivity(new Intent().setClass(this, Setting1Activity.class).putExtra(DEVICESTATE, deviceEntity));
    }

    public void settingCancelOnClicked(View view){
        startActivity(new Intent().setClass(this, Main2Activity.class).putExtra(DEVICESTATE, deviceEntity));
    }

    private boolean isWriting = false;
    public void settingConfirmOnClicked(View view){
        DeviceEntity originDeviceEntity = ((App)getApplication()).getDeviceEntity();
        WriteRegistersGenerator writeRegistersGenerator =
                new WriteRegistersGenerator(deviceEntity, originDeviceEntity);
        List<byte[]> writeRegisterFrameList = writeRegistersGenerator.getWriteRegisterFrames();
        sendBroadcast(new Intent(Actions.ACTION_SETTING).putExtra("settingdata", (Serializable)writeRegisterFrameList));
        playgif();
    }

    void playgif() {
        setContentView(View.inflate(this, R.layout.loadinggif, null));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }
}
